<?php

abstract class AbstractModel
{

    protected $_dbData;
    protected $_id;

    public function __get($name)
    {
	if (isset($this->$name)) {
	    return $this->$name;
	}

	if (isset($this->getDbData()->$name)) {
	    return $this->getDbData()->$name;
	}
	return null;
    }

    public function __set($name, $value)
    {
	if (isset($this->$name)) {
	    $this->$name = $value;
	    return $this;
	}
	$method = 'set' . ucfirst($name);
	if (method_exists($this, $method)) {
	    call_user_func(array($this, $method), $value);
	    return $this;
	}	
	$dbData = $this->getDbData();
	$dbData->$name = $value;
	$this->setDbData($dbData);
	return $this;
    }

    public function __construct($dbData = null)
    {
	$dbData = !empty($dbData) ? (object) $dbData : new stdClass();
	$this->setDbData($dbData);
	$this->_init();
    }

    abstract protected function _init();

    public function getId()
    {
	if ($this->_id === null) {
	    $dbData = $this->getDbData();
	    if (isset($dbData->id)) {
		$this->_id = $dbData->id;
	    }
	}

	return $this->_id;
    }

    public function setId($id)
    {
	$dbData = $this->getDbData();
	if (!empty($dbData)) {
	    $dbData->id = $id;
	    $this->setDbData($dbData);
	}
	$this->_id = $id;
    }

    public function setDbData(stdClass $dbData)
    {
	if ($this->_dbData === null) {
	    $this->_dbData = $dbData;
	    return $this;
	}
	foreach($dbData as $key => $value) {
	    $this->_dbData->$key = $value;
	}
	return $this;
    }

    public function getDbData($key = null)
    {
	if ($key) {
	    return (isset($this->_dbData->$key) ? $this->_dbData->$key : false);
	}
	return $this->_dbData;
    }

    public function getSqlData()
    {
	return array();
    }

}
